package com.atguigu.admin.controller;

import com.atguigu.admin.bean.Student;
import com.atguigu.admin.service.StudentService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * @author Chen Yaqi
 * @version 1.0
 */
@Controller
public class TableController {

    @Autowired
    StudentService studentService;

    /**
     * 显示编辑学生表
     * @param
     * @param
     * @return
     */
    @GetMapping("/editable_table")
    public String dynamicTable(@RequestParam(value = "pn",defaultValue = "1") Integer pn, Model model){
        // 设置每页显示条目
        int size = 5;
        // 分页查询数据
        Page<Student> studentPage = new Page<>(pn, size);
        // 分页查询的结果
        Page<Student> page = studentService.page(studentPage, null);
//        System.out.println("=============" + page.getTotal() + "===========");
        model.addAttribute("page",page);
        model.addAttribute("size",size);
        model.addAttribute("active","dataTables");
        model.addAttribute("flag","editable");
        return "table/editable_table";
    }

    /**
     * 根据id删除学生
     * @param id
     * @param pn
     * @param ra
     * @return
     */
    @GetMapping("/student/delete/{id}")
    public String deleteStudent(@PathVariable("id") Long id,
                             @RequestParam(value = "pn",defaultValue = "1") Integer pn,
                             RedirectAttributes ra){
        studentService.removeById(id);
        ra.addAttribute("pn",pn);
        return "redirect:/editable_table";
    }

    /**
     * 更新学生信息
     * @param student
     */
    @GetMapping("/student/update")
    @ResponseBody
    public void updateStudent(Student student){
        // 根据id保存student
        studentService.updateById(student);
    }


    /**
     * 保存学生信息
     */
    @GetMapping("/student/save")
    @ResponseBody
    public void saveStudent(Student student){
        studentService.saveStudent(student.getName(),student.getAge(),student.getGender(),student.getPhone());
        System.out.println(student);
    }
}
